package com.xiaozhen.jt809.utils;

import com.xiaozhen.jt809.constant.JT809BusinessConstant;
import com.xiaozhen.jt809.domain.JT809MessageHeader;
import com.xiaozhen.jt809.domain.JT809MessageInfo;

/**
 * HISTORY
 *
 * @author zhenweisheng
 * @date 2021/9/15 14:15
 * @description:
 */
public class ResponseUtil {

    /**
     * 构建返回消息
     *
     * @param messageInfo  接收到的消息
     * @param msgId        返回的业务类型
     * @param responseBody 返回的数据体
     * @return
     */
    public static JT809MessageInfo responseMessage(JT809MessageInfo messageInfo, int msgId,
                                         byte[] responseBody) {
        //设置返回的业务类型
        messageInfo.getMessageHeader().setMsgId(msgId);
        //设置返回消息的长度
        if (messageInfo.getMessageBody() == null) {
            messageInfo.getMessageHeader().setMsgLength(messageInfo.getMessageHeader().getMsgLength() + responseBody.length);
        } else {
            messageInfo.getMessageHeader().setMsgLength(messageInfo.getMessageHeader().getMsgLength() - messageInfo.getMessageBody().length + responseBody.length);
        }
        //设置返回的消息体
        messageInfo.setMessageBody(responseBody);
        return messageInfo;
    }


    /**
     * 将消息转成JT809协议格式
     */
    public static byte[] convertToBytes(JT809MessageInfo messageInfo) {
        //数据头
        JT809MessageHeader messageHeader = messageInfo.getMessageHeader();
        byte[] res = ByteArrayUtil.int2bytes(messageHeader.getMsgLength());
        res = ByteArrayUtil.append(res, ByteArrayUtil.int2bytes(messageHeader.getMsgSn()));
        //业务类型ID必须2字节 所以截取后2个字节
        byte[] msgIdBytes = ByteArrayUtil.int2bytes(messageHeader.getMsgId());
        res = ByteArrayUtil.append(res, ByteArrayUtil.subBytes(msgIdBytes, 2, 2));
        res = ByteArrayUtil.append(res, ByteArrayUtil.int2bytes(messageHeader.getMsgGnssCenterId()));
        res = ByteArrayUtil.append(res, messageHeader.getVersionFlag());
        res = ByteArrayUtil.append(res, new byte[]{(byte) messageHeader.getEncryptFlag()});
        res = ByteArrayUtil.append(res, ByteArrayUtil.int2bytes(messageHeader.getEncryptKey()));
        //数据体
        res = ByteArrayUtil.append(res, messageInfo.getMessageBody());
        //校验码
        res = ByteArrayUtil.append(res, CRC16CCITT.crcBytes(res));
        //标头
        res = ByteArrayUtil.append(new byte[]{(byte) messageInfo.getHeadFlag()}, res);
        //标尾
        res = ByteArrayUtil.append(res, new byte[]{(byte) messageInfo.getEndFlag()});
        return res;
    }

}
